<?php
/**
 * Created by PhpStorm.
 * User: thanatos
 * Date: 2017/11/30
 * Time: 下午4:02
 */

namespace frontend\controllers;


use common\models\PayLog;
use common\models\User;
use common\models\VipOrder;
use Yii;
use common\core\Controller;
use yii\db\Exception;

class PayController extends Controller{
    public $enableCsrfValidation = false;
    
    public function actionIndex()
    {
        $app = Yii::$app->wechat->app;
        $response = $app->payment->handleNotify(function($notify, $successful){
            /** @var  $notify */
            $order = VipOrder::findByOrderSn($notify->out_trade_no);
            if( !$order ){
                return '订单不存在';
            }
            
            if( $order->log ){
                return true;
            }
        
            $db = Yii::$app->db;
            $transaction = $db->beginTransaction();
    
            if( $successful ){
                $order->status = 2;
            }else{
                $order->status = 1;
            }
            $log = new PayLog();
            $log->user_id = $order->user_id;
            $log->price = $order->money;
            $log->order_sn = $order->order_sn;
            $log->pay_sn = $notify->transaction_id;
    
            $log->status = $order->status;
            
            try {
                
                // 更新用信息
                $user = User::findIdentity($order->user_id);
                if( !$user->prepareVip($order) ){
                    throw new Exception('修改会员信息失败');
                }
                
                if( !$order->save() ) throw new Exception('订单更新失败');
                if( !$log->save() ) throw new Exception('支付记录生成失败');
                
                $transaction->commit();
                return true;
            } catch(Exception $e) {
                $transaction->rollBack();
                Yii::error($e->getMessage());
                return $e->getMessage();
            }
        });
        return $response;
    }
    
}